package com.demo.servlet.utils;

import com.aspose.words.*;
import com.aspose.words.Shape;
import com.demo.servlet.entity.Staff;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/** 
* @Description:  
* @Param:  
* @return:  
* @Author: lizexin 
* @Date: 2020/12/15 
*/
public class PieChart {
    public static final String DocumentBuilderAndSaveOut = "DocumentBuilderAndSaveOut.docx";
    public static final String output = "./output/";
    public static final String school_template = "school_template.docx";
    public static final long datast = new Date().getTime();
    private static final Logger LOGGER = LoggerFactory.getLogger(PieChart.class);



    public static void main(String[] args) throws Exception {
        Document doc = new Document(school_template);
        DocumentBuilder builder = new DocumentBuilder(doc);
        long old = System.currentTimeMillis();
       /********************************************************************/
        setTitle1(builder,"一级标题");
        setTitle2(builder,"二级标题");
        setTitle3(builder,"三级标题");
       /*********************************************************************/
       //指定表格插入数据
       List<Staff> Staff = new ArrayList<>();
        Staff staff11 = new Staff();staff11.setName("信息学院"); staff11.setDoubles(new double[]{500});
        Staff staff12 = new Staff();staff12.setName("计算机学院"); staff12.setDoubles(new double[]{600});
        Staff staff13 = new Staff();staff13.setName("会计院系"); staff13.setDoubles(new double[]{700});
        Staff staff14 = new Staff();staff14.setName("肌电院系"); staff14.setDoubles(new double[]{800});
        Staff.add(staff11); Staff.add(staff12); Staff.add(staff13); Staff.add(staff14);
        for (int i = 0; i< Staff.size(); i++){
                Staff.get(i).setIndex(i+1);
            System.out.println(Staff.get(i).getIndex()+" "+Staff.get(i).getName());
        }
      /************************************************************************/
      //将表格移动
        tableTotitle(doc,"1.",0);
        tableTotitle(doc,"2.",0);
      /**********************************************************************/
      //柱状图动态插入数据
        List<Staff> entity1 = new ArrayList<>();
        double[] double_one = new double[]{100,150};
        double[] double_two = new double[]{90,150};

        Staff a = new Staff("信息学院", double_one);
        Staff b = new Staff("第二个学院", double_two);
        entity1.add(a);

        CreateChart(doc,builder,"稳定率",entity1);
     /*  ChartSeries series = CreateChart2(doc,builder,"稳定率","山东科技学院",entity1);

        SetChartSeriesDataLabel(series,entity1.size(),true);*/

        /****************************************************/
        String imageUrl = "1.jpg";
        //ImageData(doc,builder,imageUrl);

        /*设置标签*/
        /*builder.startBookmark("MyBookmark");
        builder.writeln("Text inside a bookmark.");
        builder.endBookmark("MyBookmark");*/

        Shape shape = new Shape(doc,ShapeType.IMAGE);
        shape.getImageData().setImage(imageUrl);
        shape.setWrapType(WrapType.NONE);
        shape.setBehindText(true);
        builder.moveToBookmark("MyBookmark");
        builder.insertNode(shape);
        /********************************************************************/
        String docxName = datast+DocumentBuilderAndSaveOut;
        doc.save(output+docxName);
        long now = System.currentTimeMillis();
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时



        doc.save(output + datast + DocumentBuilderAndSaveOut);

    }

    /**
     * 背景颜色
     * builder.getParagraphFormat().getShading().setBackgroundPatternColor(Color.YELLOW);//当前段落背景颜色
     * builder.getParagraphFormat().getStyle().getFont().getShading().setBackgroundPatternColor(Color.BLUE);//段落文字背景颜色（所有段落字体）
     * builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GRAY);//当前单元格背景颜色
     * builder.getFont().getShading().setBackgroundPatternColor(Color.MAGENTA);//当前段落文字背景颜色
     */
    /*字符串替换*/
   /* private static void Replace(Document doc,String oldValue,String newValue) throws Exception {
        doc.getRange().replace(oldValue,newValue,true,false);
    }*/


    /*柱状图*/
    private static void CreateChart(Document doc, DocumentBuilder builder, String Title,List<Staff> entity) throws Exception {
// 添加带有默认数据的图表。您可以指定不同的图表类型和大小
        Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);

// 形状的图表属性包含所有图表相关选项
        Chart chart = shape.getChart();
        chart.getTitle().setText(Title);//标题
// 获取图表系列收集
        ChartSeriesCollection seriesColl = chart.getSeries();
// 删除默认生成的系列.
        seriesColl.clear();
// 创建类别名称数组，在本例中我们有两个类别.
        String[] categories = new String[]{"XXX学院"};
// Adding new series. Please note, data arrays must not be empty and arrays must be the same size.
        entity.forEach(c->{
            seriesColl.add(c.getName(), categories, c.getDoubles());
            //seriesColl.add(c.getSex(), categories, c.getTestDouble());
        });
    }


    /*柱状图*/
    private static ChartSeries CreateChart2(Document doc, DocumentBuilder builder, String Title, String Category1, List<Staff> entity) throws Exception {
        ChartSeries chartSeries= null;
        Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
        Chart chart = shape.getChart();
        ChartSeriesCollection seriesColl = chart.getSeries();
        seriesColl.clear();
        String[] categories = new String[] { Category1, "平台" };
        for (int i=0;i<entity.size();i++){
            chartSeries =  seriesColl.add(Title, categories,entity.get(i).getDoubles());
            //seriesColl.add(Title, categories,c.getTestDouble());
        }
        return chartSeries;
    }

    /*柱状图中显示数据*/
        private static void SetChartSeriesDataLabel(ChartSeries series,int len,boolean showPercent){
        ChartDataLabelCollection dataLabelCollection = series.getDataLabels();
        ChartDataLabel chartDataLabel;
        for (int i = 0; i < len; i++)
        {
            chartDataLabel= dataLabelCollection.add(i);
            chartDataLabel.setShowLegendKey(true);   // 是否显示图例
            chartDataLabel.setShowLeaderLines(false);
            chartDataLabel.setShowCategoryName(true);
            chartDataLabel.setShowSeriesName(false);
            if(showPercent){
                chartDataLabel.setShowPercentage(true);// 是否显示百分号，一般饼图显示，其他不显示。
            }else {
                chartDataLabel.setShowValue(true);// 是否显示y轴的值
            }
            chartDataLabel.setSeparator("\r\n");
            //chartDataLabel.set.NumberFormat.FormatCode = "0.00%";//设置数字格式
        }
    }



    /*雷达图*/
    private static void RADAR(Document doc, DocumentBuilder builder) throws Exception {
        Shape chartShape = builder.insertChart(ChartType.RADAR, 532, 452);
        String[] strings = new String[]{
                new String("绑定率"),
                new String("上岗率"),
                new String("对口率"),
                new String("稳定率"),
                new String("统一安排率"),
                new String("签到率"),
        };

        chartShape.getChart().getSeries().clear();
        /*setStrokeColor边框颜色*/ /*setFillColor表格背景颜色*/
        chartShape.getChart().getSeries().add("2017", strings, new double[]{90, 80, 74, 95, 93, 65});
        chartShape.getChart().getSeries().add("2018", strings, new double[]{80, 70, 64, 85, 83, 55});
        chartShape.getChart().getLegend().setPosition(LegendPosition.TOP); //图标位置
        chartShape.getChart().getTitle().setText("My Cool Radar Chart");
    }

    /*饼状图*/
    private static void PieChartC(Document doc, DocumentBuilder builder) throws Exception {
        builder.insertHtml("<h1>1、分析数据</h1>");
        builder.insertHtml("<h2>1.1 数据一</h2>");
        builder.insertHtml("<h2>1.2 数据二</h2>");
        builder.insertHtml("<h3>1.2.1 计算分析</h3>");

        builder.insertHtml("<h1>2、分析数据</h1>");
        builder.insertHtml("<h2>2.1 数据一</h2>");


        Shape chartShape = builder.insertChart(ChartType.PIE, 432, 252);

        String[] strings1 = new String[]{
                new String("男"),
                new String("女"),
                new String("未知")
        };

        chartShape.getChart().getSeries().clear();
        chartShape.getChart().getLegend().setPosition(LegendPosition.TOP); //图标位置

        ChartSeries series = chartShape.getChart().getSeries().add("男女比例", strings1, new double[]{30, 60, 10});
        ChartDataLabelCollection labels = series.getDataLabels();

        labels.add(1).setShowPercentage(true);
        labels.add(1).setShowPercentage(true);
        labels.add(1).setShowValue(true);
        labels.add(1).setShowLeaderLines(false);
        labels.add(1).setSeparator(" - ");
    }

   /**设置一级标题*/
    private static void setTitle1(DocumentBuilder builder,String title1){
        try {
            builder.insertHtml("<h1 style='text-align:left;font-family:Simsun;'>"+ title1 +"</h1>");
        } catch (Exception e) {
            java.util.logging.Logger.getLogger("************制作一级标题"+title1+"出现异常***********");
            e.printStackTrace();
        }
    }

    /**设置二2级标题*/
    private static void setTitle2(DocumentBuilder builder,String title2){
        try {
            builder.insertHtml("<h2 style='text-align:left;font-family:Simsun;'>"+ title2 +"</h2>");
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    /**设置三级标题*/
    private static void setTitle3(DocumentBuilder builder,String title3){
        try {
            builder.insertHtml("<h3 style='text-align:left;font-family:Simsun;'>"+ title3 +"</h3>");
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
    /** 区别各级标题*/
    public static void setTitleS(DocumentBuilder builder,String title,String level){
        switch (level) {
            case "1":
                setTitle1(builder, title);
                break;
            case "2":
                setTitle2(builder, title);
                break;
            case "3":
                setTitle3(builder, title);
                break;
            default:
                break;
        }
    }
    /*** 制作报表段落*/
    public static void setParagraph(DocumentBuilder builder,String pragraph){
        try {
            //设置字体格式
            builder.insertHtml("<p><font face='宋体'>&nbsp;&nbsp; "+ pragraph +"</font></p>");
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
    /** 制作一个单元格并追加数据,单元格不合并 * @param width 设置单元格宽度*/
    public static void setCell(DocumentBuilder builder,Double width,String text){
        try {
            builder.insertCell();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(width==null) width = 3d;
        builder.getCellFormat().setWidth(width);
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        try {
            builder.write(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //创建表格，实现合并行、和并列、表居中、表格水平和垂直居中、设置单元格边框颜色和样式。(不实用)
    public static  void Shape(DocumentBuilder builder,Document doc)throws  Exception{
        //第一行第一列
        builder.insertCell();
        //垂直居中
        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
        //水平居中
        builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        //合并行
        builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.write("合并行");

        //第一行第二列
        builder.insertCell();
        //合并列
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);
        builder.write("合并列");

        //第一行第三列
        builder.insertCell();
        //合并列
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.getCellFormat().setHorizontalMerge(CellMerge.FIRST);

        //第一行第四列
        builder.insertCell();
        //合并列
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
        builder.endRow();

        //设置边框颜色
        //builder.getCellFormat().getBorders().getTop().setColor(System.); = System.Drawing.Color.Red;
        //设置边框样式
        //builder.getCellFormat().getBorders().getTop().setLineStyle(LineStyle.NONE);
        builder.getCellFormat().getBorders().getTop().setLineStyle(LineStyle.SINGLE);
        //endregion
        //region 添加第二行


//第二行第一列
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);

//第二行第二列
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.write("第二行第二列");

//第二行第二列
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.write("第二行第三列");

//第二行第二列
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.write("第二行第四列");
        builder.endRow();

    //endregion

//表格水平居中
        Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        table.setAlignment(TableAlignment.CENTER);
    }


    public static  void style(DocumentBuilder builder,Document doc)throws  Exception{
    }

    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = PieChart.class.getClassLoader().getResourceAsStream("com.aspose.words.lic.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }//判断水印(不实用)

  /***table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);//表格的最适行（列）高选项*/
    public static  void addexcel(Document doc,DocumentBuilder builder,int index,List<Staff> Staff)throws  Exception{
        Table table = (Table) doc.getChild(NodeType.TABLE, index, true);
        for (Staff staf : Staff) { // 替换变量
            Node deepClone = table.getLastRow().deepClone(true); //得到最后一行
            Range range = table.getLastRow().getRange();//得到值
            range.replace("index", String.valueOf(staf.getIndex()), true, true);
            range.replace("name", staf.getName(), true, true);
            range.replace("value", staf.getValue(), true, true);
            builder.moveToDocumentEnd();
            table.getRows().add(deepClone);
        }
        table.getLastRow().remove();
    }

        public static void SetBookmarkVal(DocumentBuilder builder,String bookmark, String strVal) throws Exception {
        builder.insertHyperlink(strVal, bookmark, true);
    }


    /*将表格定位到 指定标题下*/
    public static  void tableTotitle(Document doc,String startWith,int index) throws Exception {

        NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);//找到表
        if (null==tables) {
            return;
        }
        Node tableIndex = tables.get(index);
        //查找标题
        NodeCollection paras = doc.getChildNodes(NodeType.PARAGRAPH, true);
        if (null == paras) {
            return;
        }
        Paragraph insertPoint = null;
        for (Node node : paras.toArray()) {
            Paragraph p = (Paragraph)node;
            if (null!=p && p.getText().startsWith(startWith)) {
                insertPoint = p;
                break;
            }
        }
        if (null == insertPoint) {
            return;
        }
        insertPoint.getParentNode().insertAfter(tableIndex,insertPoint);
    }


    /*插入图片  不管用*/
    public static  void ImageData(Document doc,String ImageName) throws  Exception{
        Shape shape = new Shape(doc, ShapeType.IMAGE);
        //shape.
        shape.getImageData().setImage(ImageName);

        shape.setHorizontalAlignment(HorizontalAlignment.CENTER); //图片居中对齐
        //手动设置图片移动
        shape.setTop(10);
        shape.setLeft(10);


        shape.setWrapType(WrapType.INLINE);//设置图片样式，当前为嵌入型



    }

    public static  void ImageData(Document doc,DocumentBuilder builder,String imgPath) throws Exception {

        // 2.构建页面布局
        int pageCount = doc.getPageCount(); // 获取总页数
        LayoutCollector layoutCollector = new LayoutCollector(doc);
        doc.updatePageLayout();
        // 3.通过段落进行遍历（NodeType中包含各种类型可通过官网API对照）
        // https://apireference.aspose.com/words/java/com.aspose.words/NodeType
        NodeCollection runs = doc.getChildNodes(NodeType.PARAGRAPH, true);
        int tempPage = 0;
        for (int i = 0; i < runs.getCount(); i++) {
            Node r = runs.get(i);
            System.out.println("r："+r);
            // 4.找到当前段落所对应的页数
            int numPage = layoutCollector.getStartPageIndex(r);
            System.out.println("当前页数： "+numPage);
            // 5.进行图片插入
            if (numPage != tempPage) {
                // 锁定到当前段落即实现页面变换
                builder.moveTo(r);
                // insertImage中参数含义自行查询
                builder.insertImage(imgPath, RelativeHorizontalPosition.PAGE, 0, RelativeVerticalPosition.PAGE, 0, 640, 250, WrapType.NONE);
            }
            tempPage = numPage;
        }
        // 6.更新操作是将builder中修改数据更新到doc中（save方法中也会触发）
        doc.updateFields();
    }



}